import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-14
 * Time: 19:38
 */
public class dmeo3 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你要搜索的目录：");
        String rootDir = scanner.next();
        File rootFile = new File(rootDir);
        if(!rootFile.isDirectory()){
            System.out.println("目录不存在或者路径错误:");
            return;
        }
        System.out.println("请输入关键字:");
        String keyword = scanner.next();
        scanDir(rootFile, keyword);
    }
    private static void scanDir(File rootFile, String keyword) throws IOException {
        File[] files = rootFile.listFiles();
        if(files == null){
            return;
        }
        for(File file : files){
            if(file.isFile()){
                dealFile(file, keyword);
            }else{
                scanDir(file, keyword);
            }
        }
    }
    private static void dealFile(File file, String keyword) throws IOException {
        if(file.getName().contains(keyword)){
            System.out.println("文件路径:" + file.getAbsoluteFile());
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(file)){
            while (true){
                char[] buffer = new char[1024];
                int n = reader.read(buffer);
                if(n == -1){
                    break;
                }
                stringBuilder.append(buffer, 0, n);
            }
        }
        if(stringBuilder.indexOf(keyword) >= 0){
            System.out.println("文件内容包含关键字: " + file.getAbsolutePath());
        }
        return;
    }
}
